package com.butterfly.hotkey.worker.framework.disruptor;

import com.butterfly.hotkey.core.cache.ICacheManager;
import com.butterfly.hotkey.core.constant.Constants;
import com.butterfly.hotkey.core.constant.MsgTypeConst;
import com.butterfly.hotkey.core.model.AppInfoModel;
import com.butterfly.hotkey.core.model.HotKeyModel;
import com.butterfly.hotkey.core.model.msg.HotKeyMsg;
import com.butterfly.hotkey.core.util.NettyMsgUtil;
import com.butterfly.hotkey.common.disruptor.annatation.EventProcessor;
import com.butterfly.hotkey.common.disruptor.event.QueueEvent;
import com.butterfly.hotkey.common.disruptor.processor.IQueueEventProcessor;
import com.butterfly.hotkey.worker.constants.TopicConst;
import com.butterfly.hotkey.worker.framework.component.WorkerContainer;
import com.butterfly.hotkey.worker.holder.KeyCacheHolder;
import com.butterfly.hotkey.worker.util.WorkerUtil;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 处理从client端发过来的key
 *
 * @author butterfly
 * @version 1.0
 */
@Component
@EventProcessor(topic = TopicConst.TOPIC_REMOVE_KEY)
public class RemoveKeyProcessor implements IQueueEventProcessor {

    private static final Logger log = LoggerFactory.getLogger(Constants.WORKER);

    @Resource
    private ICacheManager hotKeyCache;

    @Resource
    private WorkerContainer workerContainer;

    @Override
    public void onEvent(QueueEvent event) {
        if (event == null) {
            return;
        }

        log.info("handle key remove event start");
        try {
            HotKeyModel data = (HotKeyModel) event.getData();
            handleRemoveKey(data);
        } catch (Exception e) {
            log.error("handle key remove error", e);
        }
        log.info("handle key remove event success:{}", event);
    }

    private void handleRemoveKey(HotKeyModel hotKeyModel) {
        // 删除key信息
        String cacheKey = WorkerUtil.buildCacheKey(hotKeyModel);

        // 删除hotkey缓存数据，缓存没用了
        hotKeyCache.invalidate(cacheKey);

        // 删除app关联的key的滑动窗口
        String appName = hotKeyModel.getAppName();
        ICacheManager cacheManager = KeyCacheHolder.getWindowCacheManager(appName);
        cacheManager.invalidate(cacheKey);

        // 给client推送key被删除了，客户端删除本地缓存信息
        // 删除来源：客户端本身，dashboard操作
        Map<String, AppInfoModel> clientMap = workerContainer.getClientMap();
        AppInfoModel appInfoModel = clientMap.get(appName);
        if (appInfoModel != null) {
            hotKeyModel.setRemove(true);
            HotKeyMsg hotKeyMsg = new HotKeyMsg(MsgTypeConst.RESPONSE_NEW_HOT_KEY);
            hotKeyMsg.setHotKeyModels(Lists.newArrayList(hotKeyModel));
            appInfoModel.getChannelGroup().writeAndFlush(NettyMsgUtil.buildByteBuf(hotKeyMsg));
        }
    }


}
